package com.xindaoapp.happypet.activity;

import java.util.LinkedList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.adapter.MyPostAdapter;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.bean.Message;
import com.xindaoapp.happypet.bean.MyHuiFu;
import com.xindaoapp.happypet.ui.PostDetailActivity;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshListView;

public class MyMessageActivity extends BaseLoadAnimationAcitivity implements OnClickListener {
    @ViewInject(R.id.tittle_myattention_cancel)
    private ImageButton tittle_myattention_cancel;
    @ViewInject(R.id.tittle_myattention_ok)
    private ImageButton tittle_myattention_ok;
    @ViewInject(R.id.mymessage_list)
    private PullToRefreshListView mymessage_list;
    @ViewInject(R.id.tittle_myattention_content)
    private TextView tittle_myattention_content;
    @ViewInject(R.id.noresult)
    private RelativeLayout noresult;
    @ViewInject(R.id.progress)
    private MyPostAdapter adapter;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_mymessage);
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        initClick();
        tittle_myattention_ok.setVisibility(View.GONE);
        initListView();

        loadData(currentpage);
        currentpage++;
        setLastUpdateTime();
    }

    private int currentpage = 1;

    private void initListView() {
        // myhuifu_list.setPullLoadEnabled(true);
        mymessage_list.setPullRefreshEnabled(false);
        mymessage_list.setScrollLoadEnabled(true);
        mymessage_list.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                // loadData(currentpage++);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (total.equals(arrays.size())) {
                    onLoaded();
                    Toast.makeText(getApplicationContext(), "没有更多数据了", Toast.LENGTH_SHORT).show();
                    mymessage_list.setHasMoreData(false);
                    mymessage_list.setPullLoadEnabled(false);
                    mymessage_list.setPullRefreshEnabled(false);
                    return;
                } else {
                    loadData(currentpage++);
                }
            }
        });
        mymessage_list.getRefreshableView().setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MyMessageActivity.this, PostDetailActivity.class);
                intent.putExtra(Constants.KEY_POST_TID, arrays.get(position).tid);
                startActivity(intent);
            }

        });
        setLastUpdateTime();
    }

    private final LinkedList<Message> arrays = new LinkedList<Message>();
    private String total;
    private boolean isFirst = true;

    private void loadData(int currentPage) {
        RequestParams params = new RequestParams();
        params.put("uid", UserState.getUserUid());
        params.put("page", String.valueOf(currentPage));
        params.put("pagesize", Address.PAGESIZE);
        AddClient.post(Address.HUIFU, params, new AsyncHttpResponseHandler() {
            private List<Message> array;

            @Override
            public void onSuccess(int statusCode, String content) {
                try {
                    isFirst = false;
                    onDataArrived(true);
                    MyHuiFu huifu = JSON.parseObject(content, MyHuiFu.class);
                    total = huifu.getTotal();
                    array = huifu.getArray();
                    if (array.size() > 0) {
                        arrays.addAll(array);
                    }
                    if (array != null && array.size() > 0) {
                        array.clear();
                    }
                    if (adapter == null) {
                        adapter = new MyPostAdapter(arrays, MyMessageActivity.this);
                        mymessage_list.getRefreshableView().setAdapter(adapter);
                    } else {
                        adapter.notifyDataSetChanged();
                    }
                    if (loading != null && loading.getVisibility() == View.VISIBLE) {
                        animation.stop();
                        loading.setVisibility(View.GONE);
                    }
                    if (total.equals("0")) {
                        mymessage_list.setVisibility(View.GONE);
                        noresult.setVisibility(View.VISIBLE);
                    }
                    if (Integer.parseInt(total) < 10) {
                        mymessage_list.setHasMoreData(false);
                        mymessage_list.setPullLoadEnabled(false);
                        mymessage_list.setPullRefreshEnabled(false);
                    }
                    onLoaded();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFailure(Throwable error, String content) {
                onLoaded();
                if (isFirst) {
                    onDataArrived(false);
                    SetOnLoadFailListener(new OnLoadFailListener() {
                        @Override
                        public void onLoadFail() {
                            loadData(1);
                        }
                    });
                } else {
                    onDataArrived(true);
                }
                super.onFailure(error, content);
            }
        });
    }

    private void initClick() {
        tittle_myattention_content.setText("我的回复");
        tittle_myattention_cancel.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tittle_myattention_cancel:
                finish();
                break;
            default:
                break;
        }
    }

    /** 设置加载的时间 */
    private void setLastUpdateTime() {
        String text = CommonUtil.formatPullToRefreshDate();
        mymessage_list.setLastUpdatedLabel(text);
    }

    /** 结束上拉和下拉刷新 */
    private void onLoaded() {
        mymessage_list.onPullDownRefreshComplete();
        mymessage_list.onPullUpRefreshComplete();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
    }

}
